<template>
  <!-- 新增弹框 -->
  <!-- @close="closeRoleDialog" -->
  <el-dialog
    :title="form.id ? '编辑操作' : '新增操作'"
    :visible="roleDialogVisible"
    @close="closeRoleDialog"
  >
    <!-- 表单内容 -->
    <el-form ref="roleForm" :model="form" label-width="80px" :rules="rules">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="form.description" autocomplete="off" />
      </el-form-item>
    </el-form>
    <!-- 底部 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-button size="small" @click="closeRoleDialog">取消</el-button>
      <el-button size="small" type="primary" @click="addRole">确定</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { addRoleAPI, getRoleDetailAPI, updateRoleAPI } from '@/api/setting'
export default {
  name: 'RoleSon',
  props: {
    roleDialogVisible: {
      type: Boolean
    }
  },
  data() {
    return {
      form: {
        name: '',
        description: ''
      },
      // 验证规则
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: ['blur', 'change'] }],
        description: [{ required: true, message: '请输入角色描述', trigger: ['blur', 'change'] }]
      }
    }
  },
  methods: {
    // 关闭弹窗 子传父
    closeRoleDialog() {
      this.$emit('close')
    },
    // 点击确认按钮，提交数据
    addRole() {
      // 兜底校验
      this.$refs.roleForm.validate(async valid => {
        if (!valid) return
        // 判断是编辑还是新增操作 发送添加请求
        this.form.id ? await updateRoleAPI(this.form) : await addRoleAPI(this.form)
        // 渲染页面
        this.$emit('update-list')
        // 关闭
        this.closeRoleDialog()
        // 提示
        this.$message.success(`${this.form.id ? '编辑' : '新增'}操作成功`)
        // 重置
        this.$refs.roleForm.resetFields()
        this.form = {
          name: '',
          description: ''
        }
      })
    },
    // 修改方法
    async getRoleDetail(id) {
      // 进行数据回填
      const res = await getRoleDetailAPI(id)
      // console.log(res)
      this.form = res
    }
  }
}
</script>
